﻿<template>
  <a-modal
    :title="title"
    width="95vw"
    :visible="visible"
    dialogClass="zero-modal"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <div class="issue-notes-modal-content">
        
        <div class="edit-form">
          <a-form :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <!-- #############  -->
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="单据编号">
                  <a-input disabled v-decorator="['orderNo',{rules:[{required:true,message:'单据编号不可为空！'}]}]">
                    <a-icon slot="addonAfter" @click="refreshOrderNo" type="sync" />
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="出库单类别">
                  <a-select style="width: 100%" placeholder="请选择出库单类别" v-decorator="['orderSubclass', {rules: [{ required: true, message: '请选择出库单类别！' }]}]">
                    <a-select-option v-for="(item,index) in orderSubclassData" :key="index" :value="item.id">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="出库口">
                  <a-select style="width: 100%" placeholder="请选择出库口" v-decorator="['exitPort', {rules: [{required:true,message:'出库口不可为空！'}]}]">
                    <a-select-option v-for="(item,index) in preferredPortList" :key="index" :value="item.code">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="备注">
                  <a-input placeholder="请输入备注" :max-length="30" v-decorator="['remarks']" />
                </a-form-item>
              </a-col>
            </a-row>
            <!-- #############  -->
          </a-form>
        </div>
        
        <div class="materials-table-top">
           <a-button type="primary" icon="plus" @click="onOpenChooseModal">添加物料</a-button>
           <a-input placeholder="物料编号/批次" v-model="keywords" style="display:inline-block;width:240px;"  />
        </div>
        
        <div class="materials-table">
          <div class="materials-table-head">
            <div class="materials-table-padding">
              <div class="materials-table-row">
                <div class="materials-table-cell" v-for="(item,index) in columns" :key="'materials-table-head-cell-'+index" :style="{
                  width:item.grow?'1px':(item.width?item.width:'auto'),
                  flexGrow:item.grow?item.grow:'initial',
                  flexShrink:item.grow?'initial':'0',
                  justifyContent:item.align?item.align:'center'
                }">
                  <template>{{item.name}}</template>
                </div>
              </div>
            </div>
          </div>
          <div class="materials-table-body">
            <div class="materials-table-padding">
              <a-empty v-if="showList.length<=0" />
              <div v-else class="materials-table-row" v-for="(itema,indexa) in showList" :key="'materials-table-row-'+indexa">
                <div class="materials-table-cell" v-for="(itemb,indexb) in columns" :key="'materials-table-body-cell-'+indexb" :style="{
                  width:itemb.grow?'1px':(itemb.width?itemb.width:'auto'),
                  flexGrow:itemb.grow?itemb.grow:'initial',
                  flexShrink:itemb.grow?'initial':'0',
                  justifyContent:itemb.align?itemb.align:'center'
                }">
                  <template v-if="itemb.type==='index'">{{indexa+1}}</template>
                  <template v-else-if="itemb.type==='spec'">{{`${itema.long}*${itema.wide}*${itema.high}`}}</template>
                  <template v-else-if="itemb.type==='action'">
                    <a-button type="danger" icon="delete" size="small" @click="onCancelList(indexa,itema)">删除</a-button>
                  </template>
                  <template v-else>{{itema[itemb.key]}}</template>
                </div>
              </div>
            </div>
          </div>
          
        </div>
      </div>
      
      <choose-materials-modal :visible.sync="chooseVisible" @callback="chooseCallback" />
    </a-spin>
    
    <template slot="footer">
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" :loading="confirmLoading" :disabled="list.length<=0" @click="handleSubmit">确认</a-button>
    </template>
  </a-modal>
</template>
 
<script>
  import chooseMaterialsModal from './chooseMaterialsModal.vue'
  import { FoamingChuKuOrderDetailEdit, FoamingChuKuOrderAdd, FoamingChuKuOrderEdit, FoamingChuKuOrderGetNo } from '@/api/modular/main/FoamingChuKuOrderManage'
  export default {
    components:{chooseMaterialsModal},
    emits:['callback'],
    props:{
      orderSubclassData:{
        type:Array,
        default:function(){
          return []
        }
      },
      preferredPortList:{
        type:Array,
        default:function(){
          return []
        }
      }
    },
    data () {
      return {
        id:null,
        type:'',
        labelCol: {
          span:24
        },
        wrapperCol: {
          span:24
        },
        visible: false,
        confirmLoading: false,
        title:'',
        form: this.$form.createForm(this),
        list:[],
        showList:[],
        keywords:'',
        columns:[
          { type:'index', name:'序号', width:'50px' },
          { name:'巷道', key:'aisle', width:'70px' },
          { name:'物料编号', key:'materialNo', grow:2 },
          { name:'批次', key:'batch', grow:1 },
          { name:'密度', key:'materialDensity', grow:1 },
          { type:'spec', name:'尺寸', grow:2 },
          { name:'库位号', key:'placeCode', width:'140px' },
          { name:'入库时间', key:'createdTime', width:'170px' },
          { type:'action', name:'操作', width:'80px' }
        ],
        rowkey:'materialNo',
        chooseVisible:false
      }
    },
    watch:{
      keywords(newVal,oldVal) {
        if (newVal!==oldVal) {
          this.setShowList()
        }
      }
    },
    methods: {
      // 初始化方法
      init (type,record) {
        this.type = type;
        this.visible = true
        if (type==='add'){
          this.title="新增出库单"
          this.getOrderNo((str)=>{
            if (str) {
              let _initForm = {orderNo:str} 
              this.$nextTick(()=>{
                this.form.setFieldsValue(_initForm)
              })
            }
          })
        } else {
          this.title="编辑出库单"
          this.initEdit(record)
        }
      },
      initEdit(obj){
        this.id = obj.id
        this.$loading.show()
        FoamingChuKuOrderDetailEdit({Id:this.id}).then((d)=>{
          let _initForm = {
            orderNo:d.data.orderNo,
            exitPort:d.data.exitPort,
            orderSubclass:d.data.orderSubclass,
            remarks:d.data.remarks
          } 
          this.$nextTick(()=>{
            this.form.setFieldsValue(_initForm)
          })
          this.list = d.data.wareFoamingOrderDetails
          this.setShowList()
          this.$loading.hide()
        }).catch(()=>{
          this.$loading.hide()
        })
      },
      getOrderNo(callback){
        this.$loading.show()
        FoamingChuKuOrderGetNo().then((d)=>{
          callback(d.data)
          this.$loading.hide()
        }).catch(()=>{
          this.$loading.hide()
        })
      },
      setShowList(){
        if (this.keywords) {
          let arr = []
          this.list.forEach((item)=>{
            if (item.materialNo.indexOf(this.keywords)>=0 || item.materialNo.indexOf(this.batch)>=0) {
              arr.push(item)
            }
          })
          this.showList = arr
        } else {
          this.showList = [...this.list]
        }
      },
      onOpenChooseModal(){
        this.chooseVisible = true
      },
      chooseCallback(arr){
        let newArr = [], msg = ''
        arr.forEach((item)=>{
          let ch = this.checkHasMaterial(item)
          if (ch) {
            if (msg) msg += '，'
            msg += ch
          } else {
            newArr.push(item)
          }
        })
        if (msg) {
          msg += '物料已添加过，不再重复添加！'
          this.$warning({
            title: '系统提示',
            content: msg
          });
        }
        this.list = [].concat(this.list,newArr)
        this.setShowList()
      },
      onCancelList(index,obj){
        this.showList.splice(index,1)
        let n = -1
        for (let i=0;i<this.list.length;i++) {
          if (obj[this.rowkey] === this.list[i][this.rowkey]) {
            n = i
            break
          }
        }
        if (n>=0) {
          this.list.splice(n,1)
        }
      },
      /* 验证物料是否已被添加过，是返回物料编号，否则返回空字符串 */
      checkHasMaterial(obj){
        let res = ''
        for (let i=0;i<this.list.length;i++) {
          if (obj[this.rowkey] === this.list[i][this.rowkey]) {
            res = obj[this.rowkey]
            break;
          }
        }
        return res
      },
      refreshOrderNo(){
        if (this.type==='edit') return false;
        this.getOrderNo((str)=>{
          if (str) {
            let _initForm = {orderNo:str} 
            this.$nextTick(()=>{
              this.form.setFieldsValue(_initForm)
            })
          }
        })
      },
      handleSubmit () {
       this.form.validateFields((errors, values) => {
         if (!errors) {
           this.$loading.show()
           this.handleSubmitAjax(values,(f)=>{
             this.$loading.hide()
             if (f) {
               this.$message.success('操作成功！');
               this.handleCancel()
               this.$emit('callback')
             }
           })
         }
       })
      },
      handleSubmitAjax (params,callback){
        if (this.type==='add') {
          this.handleAddAjax(params,callback)
        } else {
          this.handleEditAjax(params,callback)
        }
      },
      handleAddAjax(params,callback){
        let _params = {...params}
        _params.wareFoamingOrderDetails = this.list
        FoamingChuKuOrderAdd(_params).then(()=>{
          callback(true)
        }).catch(()=>{
          callback(false)
        })
      },
      handleEditAjax(params,callback){
        let _params = {...params}
        _params.wareFoamingOrderDetails = this.list
        _params.id = this.id;
        FoamingChuKuOrderEdit(_params).then(()=>{
          callback(true)
        }).catch(()=>{
          callback(false)
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.list = []
        this.showList = []
        this.keywords = ''
        this.visible = false
      }
    }
  }
</script>
<style lang="less" scoped>
.issue-notes-modal-content{
  height: 65vh;
  display: flex;
  flex-direction: column;
  .edit-form,.materials-table-top{
    flex-shrink: 0;
  }
  .edit-form{
    padding: 20px 16px 0 16px;
  }
  .materials-table-top{
    padding: 0 16px 8px 16px;
  }
  .materials-table{
    height: 1px;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding-bottom: 12px;
    .materials-table-head{
      flex-shrink: 0;
      .materials-table-cell{
        background-color:#fafafa;
      }
    }
    .materials-table-body{
      height: 1px;
      flex-grow: 1;
      overflow: auto;
    }
    .materials-table-padding{
      padding: 0 16px;
    }
    .materials-table-row{
      box-sizing: border-box;
      width: 100%;
      display: flex;
      border-bottom: 1px solid #e8e8e8;
      .materials-table-cell{
        display: flex;
        align-items: center;
        padding: 6px 8px;
        word-break:break-all;
        word-wrap:break-word; 
      }
    }
  }
}
</style>